package com.core.toolkit.jwt;

import com.alibaba.fastjson2.JSON;
import com.core.pojo.User.dto.UserInfoDTO;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * JWT 工具类
 */
@Slf4j
@Component
public class JwtUtil {

    private static final long EXPIRATION = 8640000L * 1000; //L是指毫秒，86400L*1000是24小时,即这里的8640000L*1000指一百天（测试用）
    public static final String TOKEN_PREFIX = "Bearer ";
    public static final String ISS = "denis";
    public static final String SECRET = "SecretKey039245678901232039487623456783092349288901402967890140939393";
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET.getBytes());

    /**
     * 生成token
     */
    public static String generateToken(UserInfoDTO userInfoDTO) {
        String jwtToken = Jwts.builder()
                .signWith(SECRET_KEY, SignatureAlgorithm.HS512)
                .setIssuedAt(new Date())
                .setIssuer(ISS)
                .setSubject(JSON.toJSONString(userInfoDTO))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION ))
                .compact();
        return "Bearer " + jwtToken;
    }

    /**
     * 解析用户 Token
     *
     * @return 用户信息
     */
    public static UserInfoDTO parseJwtToken(String authHeader) {
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(TOKEN_PREFIX)) {
            return null;
        }
        String jwtToken = authHeader.substring(TOKEN_PREFIX.length());
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)  // 使用相同的SecretKey对象
                    .build()
                    .parseClaimsJws(jwtToken);

            String subject = claimsJws.getBody().getSubject();
            return JSON.parseObject(subject, UserInfoDTO.class);

        } catch (ExpiredJwtException e) {
            log.warn("Token已过期: {}", e.getMessage());
        } catch (UnsupportedJwtException | MalformedJwtException e) {
            log.warn("无效的Token格式: {}", e.getMessage());
        } catch (SignatureException e) {
            log.warn("签名验证失败: {}", e.getMessage());
        } catch (Exception e) {
            log.error("Token解析错误", e);
        }
        return null;
    }
}
